package com.zy.common.core;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.zy.common.core.constant.Constants;
import com.zy.common.core.enums.ErrorEnums;
import lombok.Data;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 响应信息主体
 */
@Data
public class R<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 成功
     */
    public static final int SUCCESS = Constants.SUCCESS;

    /**
     * 失败
     */
    public static final int FAIL = Constants.FAIL;

    private int code;

    private String msg;

    //    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private T data;

//    @JsonInclude(JsonInclude.Include.NON_EMPTY)
//    private Map<String, Object> map;

    public static <T> R<T> ok() {
        return restResult(null, SUCCESS, null);
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, SUCCESS, Constants.SUCCESS_MSG);
    }

    public static <T> R<T> ok(T data, String msg) {
        return restResult(data, SUCCESS, msg);
    }

    public static <T> R<T> fail() {
        return restResult(null, FAIL, null);
    }

    public static <T> R<T> fail(String msg) {
        return restResult(null, FAIL, msg);
    }

    public static <T> R<T> fail(T data) {
        return restResult(data, FAIL, null);
    }

    public static <T> R<T> fail(int code, String msg) {
        return restResult(null, code, msg);
    }

    public static <T> R<T> fail(ErrorEnums enums) {
        return restResult(null, enums.getCode(), enums.getDesc());
    }

    private static <T> R<T> restResult(T data, int code, String msg) {
        R<T> apiResult = new R<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }

    public R put(String key, Object value) {
        Map<String, Object> var = (Map<String, Object>) this.data;
        if (var == null) {
            var = new HashMap<>();
        }
        var.put(key, value);
        this.data = (T) var;
        return this;
    }
}
